import cgi

from google.appengine.api import users
from google.appengine.ext import db

from gaeo.controller import BaseController

from model.issue import Issue
from model.status import Status

class StatusController(BaseController):
    def before_action(self):
        if not users.get_current_user():
            self.redirect(users.create_login_url('/'))

    def create(self):
        r = Status(
            # Uncomment all required properties here.
            title = self.params.get('title', None),
            description = self.params.get('description', None),
        )
        for prop in Status.properties():
            if prop in self.params:
                setattr(r, prop, self.params.get(prop))
        r.put()
        self.redirect('/status')

    def destroy(self):
        r = Status.get(self.params.get('id'))
        if r is not None:
            r.delete()
        self.redirect('/status')

    def edit(self):
        r = Status.get(self.params.get('id'))
        if r:
            for prop in Status.properties():
                setattr(self, prop, getattr(r, prop))
        else:
            self.redirect('/status')

    def index(self):
        query = Status.all()
        query.filter('owner =', users.get_current_user())
        self.result = query.fetch(limit=1000)

    def new(self):
        pass

    def show(self):
        r = Status.get(self.params.get('id'))
        if r:
            for prop in Status.properties():
                setattr(self, prop, getattr(r, prop))
            self.issue_set = r.issue_set.order("-modification")
        else:
            self.redirect('/status')

    def update(self):
        r = Status.get(self.params.get('id'))
        for prop in Status.properties():
            if prop in self.params:
                setattr(r, prop, self.params.get(prop))
        r.put()
        self.redirect('/status/show/%s' % (r.key()))
